#include <stdio.h>
#include <unistd.h>

//SPI
#include "wifiiot_spi.h"
#include "hal_wifiiot_spi.h"
#include "hi_spi.h"

#include "spi.h"

void SPI0_Init(void)
{
    hi_u32 ret;

	//SPI 初始化
    WifiIotSpiCfgInitParam init_param; //主从模式：主
    init_param.isSlave = HI_FALSE;
    WifiIotSpiCfgBasicInfo spi_cfg_basic_info; //spi cfg 参数设置
    spi_cfg_basic_info.cpol = WIFI_IOT_SPI_CFG_CLOCK_CPOL_0; /* 极性 */
    spi_cfg_basic_info.cpha = WIFI_IOT_SPI_CFG_CLOCK_CPHA_0; /* 相位 */
    /* Motorola protocol(成功) */  /* Texas Instruments protocol(失败) */  /* Microwire protocol(失败) */
    spi_cfg_basic_info.framMode = WIFI_IOT_SPI_CFG_FRAM_MODE_MOTOROLA; /* 帧协议 */
    spi_cfg_basic_info.dataWidth = WIFI_IOT_SPI_CFG_DATA_WIDTH_E_8BIT; /* 数据位宽 */
    spi_cfg_basic_info.endian = WIFI_IOT_SPI_CFG_ENDIAN_LITTLE; /* 小端 */
    spi_cfg_basic_info.freq = 1000000; /* 频率 */ //1M 2M 8M
    ret = SpiInit(SPI_PORT, init_param, &spi_cfg_basic_info);
    if (ret != 0) {
        printf("Failed to init spi %d! Err code = %d\r\n", SPI_PORT, ret);
    }
    else
    {
        printf("Initialize spi %d successfully\r\n", SPI_PORT);
    }

    // SPI0_ReadWriteByte(0xFF); //启动传输
}

unsigned char SPI0_ReadWriteByte(unsigned char TxData)
{
    hi_u32 ret;
    unsigned char RxData;
    ret = hi_spi_host_writeread(SPI_PORT, &TxData, &RxData, 1);
    if(ret != 0)
    {
        printf("hi_spi_host_writeread failed\r\n");
    }
    return RxData;
}